/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018/11/21 Time: 10:03
 *
 * 登录
 */

import React, {Component} from 'react';
import {
    View,
    SafeAreaView,
    Text,
    TouchableOpacity,
    Image,
    TextInput,
    YellowBox, AsyncStorage, Modal
} from 'react-native';
import {connect} from 'react-redux';
import {styles} from './LoginScreen.Style';
import {COLOR_HEADER_END, COLOR_HEADER_START, FONT_COLOR_SUB_TITLE} from "../../../constant/PHColors"
import LinearGradient from "react-native-linear-gradient"
import {doLogin,doCache,doAlinarg,doButtonRight} from "./Actions"
import {FetchStatus} from "../../../configuration/RequestConfiguration"
import {doDisplayWarnMessage} from "../../../component/Message/Action"
import {ReturnStatus} from "../../../configuration/ReturnStatus"
import LoadingView from "../../../component/LoadingView/LoadingView"
import User from '../../../model/User/User'
import {doSetToken,doSetCache,doSetUserSession} from "../AuthScreen/Action"
import {JPushSetTag,JPushSetAlias} from "../../../util/JPush/JPushUtil"
import global from "../../../configuration/global"
import {creWebSocket} from "../../../configuration/global"
import Sound from 'react-native-sound';


class LoginScreen extends Component {

    static navigationOptions = {
        header: null
    };

    // 构造
    constructor(props) {
        super(props);

        YellowBox.ignoreWarnings(
            ['Warning: isMounted(...) is deprecated', 'Module RCTImageLoader'
            ]);


        // 初始状态
        this.state = {
            username: '',
            password: '',
            hotelId: "",
            ProductAPIUrl:"",
            // ProductAPIUrl_spare:"",
            checkModalVisible:false,
        };

        AsyncStorage.getItem("hotelId").then((value) => {
            this.setState({
                hotelId: value||""
            })
        }).catch(() => {
            return ""
        });

        AsyncStorage.getItem("ProductAPIUrl").then((value) => {
            this.setState({
                ProductAPIUrl: value||""
            })
            global.AppRequestPath=value;
        }).catch(() => {
            return ""
        });

        // AsyncStorage.getItem("ProductAPIUrl_spare").then((value) => {
        //     this.setState({
        //         ProductAPIUrl_spare: value||""
        //     })
        //     global.AppRequestPath_spare=value;
        // }).catch(() => {
        //     return ""
        // });

        AsyncStorage.getItem("username").then((valueUsername) => {
            this.setState({
                username:valueUsername||"",
            })
        })

        AsyncStorage.getItem("password").then((valuePassword) => {
            this.setState({
                password:valuePassword||"",
            })
        })

        // //声音
        // const s = new Sound('http://hao.haolingsheng.com/ring/000/985/e618dfdcae743091cbeccb21d6289afa.mp3',null, (e) => {
        //     if (e) {
        //         alert("播放失败")
        //         return;
        //     }
        //     s.play(() => s.release());
        // });
    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;
        if (nextProps.onLogin !== this.props.onLogin && nextProps.onLogin.fetchStatus === FetchStatus.Success) {
            if (nextProps.onLogin.RETURN === ReturnStatus.Success) {

                dispatch(doSetToken(nextProps.onLogin.TOKEN));

                dispatch(doSetUserSession(nextProps.onLogin.userid,nextProps.onLogin.dep,nextProps.onLogin.hotelId));

                dispatch(doAlinarg(nextProps.onLogin.hotelId));

                dispatch(doCache(nextProps.onLogin.hotelId));

                dispatch(doButtonRight(nextProps.onLogin.hotelId));

                User.saveUser(nextProps.onLogin.TOKEN,nextProps.onLogin, () => {

                })

            } else {
                dispatch(doDisplayWarnMessage(nextProps.onLogin.MSG))
            }
        }


        if (nextProps.onAlinarg !== this.props.onAlinarg && nextProps.onAlinarg.fetchStatus === FetchStatus.Success) {
            if (nextProps.onAlinarg.RETURN === ReturnStatus.Success) {

                let alinarg_arr = nextProps.onAlinarg.DATA;
                User.saveAlinarg(JSON.stringify(alinarg_arr), () => {
                });

            } else {
                dispatch(doDisplayWarnMessage(nextProps.onGetCache.MSG))
            }
        }

        if (nextProps.onButtonRight !== this.props.onButtonRight && nextProps.onButtonRight.fetchStatus === FetchStatus.Success) {
            if (nextProps.onButtonRight.RETURN === ReturnStatus.Success) {

                let buttonRight_arr = nextProps.onButtonRight.button;
                User.saveButtonRight(JSON.stringify(buttonRight_arr), () => {
                });

                let loginRight_arr = nextProps.onButtonRight['login']||"";
                User.saveLoginRight(loginRight_arr, () => {
                });

            } else {
                dispatch(doDisplayWarnMessage(nextProps.onGetCache.MSG))
            }
        }



        if (nextProps.onGetCache !== this.props.onGetCache && nextProps.onGetCache.fetchStatus === FetchStatus.Success) {
            if (nextProps.onGetCache.RETURN === ReturnStatus.Success) {

                dispatch(doSetCache(nextProps.onGetCache));

                User.saveCache(nextProps.onGetCache, () => {
                });
                AsyncStorage.setItem("username",this.state.username).then((valueUsername) => {})
                AsyncStorage.setItem("password",this.state.password).then((valuePassword) => {})
                AsyncStorage.setItem("TOKEN",nextProps.onLogin.TOKEN).then((valueTOKEN) => {})

                if(nextProps.onLogin.tags)
                    JPushSetTag([nextProps.onLogin.tags])
                if(nextProps.onLogin.alias)
                    JPushSetAlias(nextProps.onLogin.alias);

                console.log(nextProps.onLogin.tags)
                console.log(nextProps.onLogin.alias)

                let qms_role_arr = nextProps.onLogin.qms_role.split(',')

                //推送
                creWebSocket(this.state.hotelId,this.state.username)

                if(qms_role_arr.indexOf("TEST")>=0){ //测试页面
                    this.props.navigation.navigate('AlertNavigator',{transition:'forInitial'});
                }else if(qms_role_arr.indexOf("ADMIN")>=0){ //客房员工
                    // this.props.navigation.navigate('MainNavigator');
                    this.props.navigation.navigate('Homepage_repair',{transition:'forInitial'});
                }else{
                    this.props.navigation.navigate('HousekeeperMainNavigator');
                }

            } else {
                dispatch(doDisplayWarnMessage(nextProps.onGetCache.MSG))
            }
        }

    }

    render() {
        let {dispatch, onLogin,onGetCache} = this.props;

        if (onLogin.fetchStatus === FetchStatus.Start || onGetCache.fetchStatus === FetchStatus.Start) {
            return <LoadingView/>
        } else
            return (
                <SafeAreaView style={styles.container}>
                    <View style={styles.underLoginView}>
                        <TouchableOpacity style={styles.underLoginRightT} activeOpacity={0.9} onPress={this._onClickChooseAccount.bind(this)}>
                            <View style={styles.underLoginRightT}>
                                <Text style={styles.forgetText}>
                                    设置
                                </Text>
                            </View>
                        </TouchableOpacity>
                    </View>

                    <View style={{flex: 1}}>
                        <View style={styles.topViewContainer}>
                            <Image style={styles.topImage} source={require('../../../resource/login/logo.png')}/>
                        </View>

                        <View style={styles.centerView}>
                            {/* 用户名*/}
                            <View style={[styles.textInputContainer, {marginTop: 15}]}>
                                <View style={styles.usernameImage}>
                                    <Image style={styles.userImage} source={require('../../../resource/login/dl_user.png')}/>
                                </View>
                                <View style={styles.usernameContainer}>
                                    <TextInput
                                        style={styles.input}
                                        placeholder={'手机号/账号'}
                                        placeholderTextColor={FONT_COLOR_SUB_TITLE}
                                        underlineColorAndroid={"transparent"}
                                        numberOfLines={1}
                                        autoCapitalize={'characters'}
                                        clearButtonMode={'while-editing'}
                                        defaultValue={
                                            this.state.username
                                        }
                                        onChangeText={text => {
                                            this.setState({
                                                username: text.toUpperCase()
                                            })
                                        }}
                                    />
                                </View>
                                <TouchableOpacity activeOpacity={0.8} onPress={() => {

                                }}/>
                                <View style={styles.showMoreImage}>
                                    <Image style={{width: 14, height: 8}} source={require('../../../resource/login/dl_chevron-down.png')}/>
                                </View>
                            </View>

                            {/* 密码 */}
                            <View style={[styles.textInputContainer, {marginTop: 15}]}>
                                <View style={styles.usernameImage}>
                                    <Image style={styles.userImage} source={require('../../../resource/login/dl_lock.png')}/>
                                </View>

                                <View style={styles.usernameContainer}>
                                    <TextInput
                                        style={styles.input}
                                        placeholder={'密码'}
                                        placeholderTextColor={FONT_COLOR_SUB_TITLE}
                                        underlineColorAndroid={"transparent"}
                                        secureTextEntry={true}
                                        numberOfLines={1}
                                        clearButtonMode={'while-editing'}
                                        defaultValue={
                                            this.state.password
                                        }
                                        onChangeText={text => {
                                            this.setState({
                                                password: text
                                            })
                                        }}
                                    />
                                </View>
                            </View>

                            <TouchableOpacity activeOpacity={0.9} onPress={this._onClickLogin.bind(this)}>
                                <LinearGradient start={{x: 0, y: 0}} end={{x: 1, y: 0}} colors={[COLOR_HEADER_START, COLOR_HEADER_END]} style={styles.loginContainer}>
                                    <Text style={styles.loginText}>
                                        登录
                                    </Text>
                                </LinearGradient>
                            </TouchableOpacity>

                            <View style={styles.underLoginView}>
                                <TouchableOpacity style={styles.underLoginLeft} activeOpacity={0.7} onPress={() => {
                                }}>
                                    <View style={styles.underLoginLeft}>
                                        <Image style={{width: 18, height: 18}} source={require('../../../resource/login/dl_yixuan.png')}/>
                                        <Text style={styles.rememberText}>
                                            记住密码
                                        </Text>
                                    </View>
                                </TouchableOpacity>

                                <TouchableOpacity style={styles.underLoginRight} activeOpacity={0.7} onPress={() => {
                                }}>
                                    <View style={styles.underLoginRight}>
                                        {/*<Text style={styles.forgetText}>*/}
                                            {/*忘记密码*/}
                                        {/*</Text>*/}
                                    </View>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>

                    <Modal visible={this.state.checkModalVisible} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()}>
                        <TouchableOpacity style={{flex: 1}} activeOpacity={1}  onPress={()=>{
                            //this.onRequestClose();
                        }}>
                            <View style={styles.modalContainer}>
                                <View style={styles.modalBox} >
                                        <View style={styles.modalTitle}>
                                            <Text style={styles.modalTitleTextNum}>
                                                设置
                                            </Text>
                                        </View>
                                        <View style={styles.modalCenter}>
                                            <View style={[styles.textInputContainer,{marginTop: 10}]}>
                                                <View style={styles.usernameImage}>
                                                    <Image style={styles.userImage} source={require('../../../resource/login/logo.png')}/>
                                                </View>
                                                <View style={styles.usernameContainer}>
                                                    <TextInput
                                                        style={styles.input}
                                                        placeholder={'服务器'}
                                                        placeholderTextColor={FONT_COLOR_SUB_TITLE}
                                                        underlineColorAndroid={"transparent"}
                                                        numberOfLines={1}
                                                        clearButtonMode={'while-editing'}
                                                        defaultValue={
                                                           this.state.ProductAPIUrl
                                                        }
                                                        onChangeText={text => {
                                                            this.setState({
                                                                ProductAPIUrl: text
                                                            })
                                                        }}
                                                    />
                                                </View>
                                            </View>
                                            {/*<View style={[styles.textInputContainer,{marginTop: 10}]}>
                                                <View style={styles.usernameImage}>
                                                    <Image style={styles.userImage} source={require('../../../resource/login/logo.png')}/>
                                                </View>
                                                <View style={styles.usernameContainer}>
                                                    <TextInput
                                                        style={styles.input}
                                                        placeholder={'备用服务器'}
                                                        placeholderTextColor={FONT_COLOR_SUB_TITLE}
                                                        underlineColorAndroid={"transparent"}
                                                        numberOfLines={1}
                                                        clearButtonMode={'while-editing'}
                                                        defaultValue={
                                                            this.state.ProductAPIUrl_spare
                                                        }
                                                        onChangeText={text => {
                                                            this.setState({
                                                                ProductAPIUrl_spare: text
                                                            })
                                                        }}
                                                    />
                                                </View>
                                            </View>*/}
                                            <View style={[styles.textInputContainer,{marginTop: 10}]}>
                                                <View style={styles.usernameImage}>
                                                    <Image style={styles.userImage} source={require('../../../resource/login/dl_user.png')}/>
                                                </View>
                                                <View style={styles.usernameContainer}>
                                                    <TextInput
                                                        style={styles.input}
                                                        placeholder={'酒店号'}
                                                        placeholderTextColor={FONT_COLOR_SUB_TITLE}
                                                        underlineColorAndroid={"transparent"}
                                                        numberOfLines={1}
                                                        clearButtonMode={'while-editing'}
                                                        defaultValue={
                                                            this.state.hotelId
                                                        }
                                                        onChangeText={text => {
                                                            this.setState({
                                                                hotelId: text
                                                            })
                                                        }}
                                                    />
                                                </View>
                                            </View>
                                        </View>
                                        <View style={styles.underLoginView}>
                                            <TouchableOpacity style={styles.modalUnderLoginLeft} activeOpacity={0.9} onPress={this._onClickSaveSetUp.bind(this)}>
                                                <LinearGradient start={{x: 0, y: 0}} end={{x: 1, y: 0}} colors={[COLOR_HEADER_START, COLOR_HEADER_END]} style={styles.saveSetUp}>
                                                    <Text style={styles.saveSetUpText}>
                                                        保存
                                                    </Text>
                                                </LinearGradient>
                                            </TouchableOpacity>
                                            <TouchableOpacity style={styles.modalUnderLoginRight} activeOpacity={0.9} onPress={this._modalCancel.bind(this)}>
                                                <LinearGradient start={{x: 0, y: 0}} end={{x: 1, y: 0}} colors={[COLOR_HEADER_START, COLOR_HEADER_END]} style={styles.saveSetUp}>
                                                    <Text style={styles.saveSetUpText}>
                                                        取消
                                                    </Text>
                                                </LinearGradient>
                                            </TouchableOpacity>
                                        </View>
                                </View>
                            </View>
                        </TouchableOpacity>
                    </Modal>

                </SafeAreaView>
            )
    }

    /**
     * 登录按钮点击
     * @private
     */
    _onClickLogin() {
        // this.props.navigation.navigate('MainNavigator');
        let {dispatch} = this.props;
        // JPushModule.getRegistrationID(registrationId => {
        //     alert(registrationId)
        // });
        dispatch(doLogin(this.state.username, this.state.password, this.state.hotelId));

    }

    /**
     * 设置点击
     * @private
     */
    _onClickChooseAccount() {
       this.setState({
           checkModalVisible:true,
       })
    }

    /**
     * 模态取消
     * @private
     */
    _modalCancel(){
        this.setState({
            checkModalVisible:false,
        })

        AsyncStorage.getItem("hotelId").then((valueHotelId) => {
            this.setState({
                hotelId:valueHotelId,
            })
        })

        AsyncStorage.getItem("ProductAPIUrl").then((valueProductAPIUrl) => {
            this.setState({
                ProductAPIUrl:valueProductAPIUrl,
            })

        })

        // AsyncStorage.getItem("ProductAPIUrl_spare").then((valueProductAPIUrl_spare) => {
        //     this.setState({
        //         ProductAPIUrl_spare:valueProductAPIUrl_spare,
        //     })
        //
        // })
    }

    /**
     * 模态关闭
     * @private
     */
    onRequestClose(){
        this.setState({
            checkModalVisible:false,
        })
    }

    /**
     * 保存设置
     * @private
     */
    _onClickSaveSetUp(){
        let header = "http://";
        if(this.state.ProductAPIUrl.indexOf("https://")>=0){
            header = "https://";
        }

        if(this.state.ProductAPIUrl.indexOf("http://")>=0)
            this.state.ProductAPIUrl=this.state.ProductAPIUrl.replace("http://","");
        if(this.state.ProductAPIUrl.indexOf("https://")>=0)
            this.state.ProductAPIUrl=this.state.ProductAPIUrl.replace("https://","");
        if(this.state.ProductAPIUrl.indexOf("/qms/mobile")>=0)
            this.state.ProductAPIUrl=this.state.ProductAPIUrl.replace("/qms/mobile","");
        global.AppRequestPath=header+this.state.ProductAPIUrl+"/qms/mobile"
        AsyncStorage.setItem("hotelId",this.state.hotelId).then((valueHotelId) => {})
        AsyncStorage.setItem("ProductAPIUrl",global.AppRequestPath).then((valueProductAPIUrl) => {})
        this.state.ProductAPIUrl =  global.AppRequestPath
        /*if(this.state.ProductAPIUrl_spare.contains("http://"))
            this.state.ProductAPIUrl_spare=this.state.ProductAPIUrl_spare.replace("http://","");
        if(this.state.ProductAPIUrl_spare.contains("/qms/mobile"))
            this.state.ProductAPIUrl_spare=this.state.ProductAPIUrl_spare.replace("/qms/mobile","");
        global.AppRequestPath_spare="http://"+this.state.ProductAPIUrl_spare+"/qms/mobile"
        AsyncStorage.setItem("ProductAPIUrl_spare",global.AppRequestPath_spare).then((valueProductAPIUrl_spare) => {})*/
        this.onRequestClose();
    }
}

const props = state => {
    return {
        onLogin: state.onLogin,
        onGetCache: state.onGetCache,
        onAlinarg: state.onAlinarg,
        onButtonRight:state.onButtonRight,
    }
};

export default LoginScreen = connect(props)(LoginScreen);



